<?php
namespace app\system\controller;

use app\common\model\CategoryModel;
use think\Cache;
use think\Request;

class CategoryController extends BaseController
{

    private $mid;
    private $categoryModel;
    private $categoryCache;
    private $moudleCache;
    private $tableName;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->mid = $this->request->param('mid/d');
        $this->categoryModel = new CategoryModel();
        $this->categoryCache = Cache::get('category_'.$this->mid);
        $this->moudleCache = Cache::get('moudle');
        $this->tableName = $this->moudleCache[$this->mid]['table_name'];
    }

    /**
     * 栏目首页
     */
    public function index()
    {
        $this->assign('category', $this->categoryCache);
        return $this->fetch();
    }

    /**
     * 栏目的添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            try{
                $data = $this->request->param();
                if ($this->request->has('is_batch')) { //批量模式
                    $data['cat_name'] = $this->request->param('cat_names');
                }
                $result = $this->validate($data, [
                    'cat_name|栏目名称' => 'require',
                    'cat_tpl|栏目模板'  => 'require',
                ]);
                if ($result !== true) {
                    exception($result,40001);
                }
                if ($this->request->has('is_batch')) {
                    $catNames = explode("\r\n", $data['cat_name']);
                    $dataList = [];
                    foreach ($catNames as $v) {
                        unset($data['cat_names']);
                        unset($data['is_batch']);
                        $data['cat_name'] = $v;
                        $dataList[]       = $data;
                    }
                    $this->categoryModel->saveAll($dataList);
                } else {
                    $this->categoryModel->addData($data);
                }
                $this->categoryModel->updateCache($this->mid);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('添加成功', url('index',['mid'=>$this->mid]));
        }
        $this->assign('table_name', $this->tableName);
        $this->assign('category', $this->categoryCache);
        return $this->fetch();
    }

    /**
     * 修改栏目
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            try{
                $data   = $this->request->param();
                $result = $this->validate($data, [
                    'cat_name|栏目名称' => 'require',
                    'cat_tpl|栏目模板'  => 'require',
                ]);
                if ($result !== true) {
                    exception($result,40001);
                }
                $this->categoryModel->editData($data);
                $this->categoryModel->updateCache($this->mid);
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功！', url('index',['mid'=>$this->mid]));
        }
        $cid      = $this->request->param('cid/d', 0);
        $info     = $this->categoryCache[$cid];
        $category = [];
        foreach ($this->categoryCache as $k => $v) {
            //父栏目select状态
            $v['selected'] = $info['pid'] == $v['cid'] ? 'selected' : '';
            //子栏目disabled
            $disabled      = \org\util\TreeUtil::isChild($this->categoryCache, $v['cid'], $cid, 'cid') || $cid == $v['cid'] ? 'disabled' : '';
            $v['disabled'] = $disabled;
            $category[]    = $v;
        }
        $this->assign('table_name', $this->tableName);
        $this->assign('category', $category);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除栏目
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            try{
                $mid = $this->request->param('mid/d');
                $cid = $this->request->param('cid/d');
                if ($this->categoryModel->where('pid', $cid)->find()) {
                    exception('该栏目还存在下级分类，不允许删除！',40001);
                } else {
                    if (cms_moudle($mid)->where('cid', $cid)->find()) {
                        exception('该栏目还存在数据，不允许删除！',40001);
                    }
                    $this->categoryModel->delData($cid);
                    $this->categoryModel->updateCache($this->mid);
                }
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('删除成功！', url('index',['mid'=>$this->mid]));
        }
    }

    /**
     * 更新站点缓存
     */
    public function updateCache()
    {
        $this->categoryModel->updateCache($this->mid);
        $this->success('操作成功！', url('index',['mid'=>$this->mid]));
    }

    /**
     *栏目排序
     */
    public function updateOrder()
    {
        try{
            $listOrder = $this->request->param('list_order/a');
            foreach ($listOrder as $cid => $order) {
                $cid        = intval($cid);
                $order      = intval($order);
                $dataList[] = ["cid" => $cid, "cat_order" => $order];
            }
            $this->categoryModel->saveAll($dataList);
            $this->categoryModel->updateCache($this->mid);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('排序成功！', url('index',['mid'=>$this->mid]));
    }
    /**
     *栏目模板批量设置
     */
    public function updateTpl()
    {
        try{
            $listTpl = $this->request->param('list_tpl/a');
            foreach ($listTpl as $cid => $cat_tpl) {
                $cid        = intval($cid);
                $dataList[] = ["cid" => $cid, "cat_tpl" => $cat_tpl];
            }
            $this->categoryModel->saveAll($dataList);
            $this->categoryModel->updateCache($this->mid);
        } catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('栏目模板设置成功！', url('index',['mid'=>$this->mid]));
    }

}
